package ThreadCommunication.volatiletest;

/**
 * @author dycong
 * @date 2018/5/5 19:50
 */
public class MethodThree {
    /**
     *todo volatile修饰的变量值直接存在main memory里面，子线程对该变量的读写直接写入main memory，
     *todo 而不是像其它变量一样在local thread里面产生一份copy。volatile能保证所修饰的变量对于多个线程可见性，即只要被修改，其它线程读到的一定是最新的值。
     */
    private volatile ThreadToGo threadToGo = new ThreadToGo();

    class ThreadToGo {
        int value = 1;
    }

    public Runnable newThreadOne() {
        return new Runnable() {
            public void run() {
                for (int i = 0; i <51; i=i+2) {
                    while(threadToGo.value==2){}
                    System.out.println("one");
                    threadToGo.value=2;
                }
            }
        };
    }

    public Runnable newThreadTwo() {

        return new Runnable() {

            public void run() {
                for (int i = 0; i < 26; i++) {
                    while(threadToGo.value==1){}
                    System.out.println("two");
                    threadToGo.value=1;
                }
            }
        };
    }

    public static void main(String args[]) throws InterruptedException {
        MethodThree three = new MethodThree();
        new Thread(three.newThreadOne()).start();
        new Thread(three.newThreadTwo()).start();
    }
}
